using System;
using UnityEngine;

namespace AGame.TabOrm.TabOrmAttributeExpand
{
    public class ColorTabField : TabField
    {
        public bool HaveSharp;
        public bool HaveAlpha;

        public override Func<string, object> GetStrToObjFunc(Type tabType, Type targetType)
        {
            if (targetType == typeof(Color?))
            {
                if (HaveSharp)
                {
                    return StrToColorNullableHaveSharp;
                }

                return StrToColorNullableNotHaveSharp;
            }

            if (targetType == typeof(Color))
            {
                if (HaveSharp)
                {
                    return StrToColorHaveSharp;
                }

                return StrToColorNotHaveSharp;
            }

            return default;
        }

        public override Func<object, string> GetObjToStrFunc(Type tabType, Type targetType)
        {
            if (targetType == typeof(Color) || targetType == typeof(Color?))
            {
                return ColorToStr;
            }

            return default;
        }


        private static object StrToColorHaveSharp(string colorStr)
        {
            return ColorUtility.TryParseHtmlString(colorStr, out var outColor) ? outColor : Color.white;
        }

        private static object StrToColorNotHaveSharp(string colorStr)
        {
            return ColorUtility.TryParseHtmlString("#" + colorStr, out var outColor) ? outColor : Color.white;
        }

        private static object StrToColorNullableHaveSharp(string colorStr)
        {
            return ColorUtility.TryParseHtmlString(colorStr, out var outColor) ? outColor : (Color?) null;
        }

        private static object StrToColorNullableNotHaveSharp(string colorStr)
        {
            return ColorUtility.TryParseHtmlString("#" + colorStr, out var outColor) ? outColor : (Color?) null;
        }

        private string ColorToStr(object data)
        {
            if (!(data is Color color))
            {
                return string.Empty;
            }

            var colorStr = HaveAlpha ? ColorUtility.ToHtmlStringRGBA(color) : ColorUtility.ToHtmlStringRGB(color);
            return HaveSharp ? "#" + colorStr : colorStr;
        }
    }
}